const dbconfig = require('../db/dbconfig.js');
const md5 = require('md5-node');
const operation = require('./operation')
const Token = require('../token/token')

// 登录业务实习
handleLogin=(req,res)=>{
        let {type} = req.params;
        console.log(req.params);
        let {username,password} = req.body;
        let sql = `select * from ${type} where username=? and password=?`;
        // let sql = `select * from users where username=? and password=?`;
        // 使用md5加密
        password = md5(password);
         
        let arr=[username,password];
        
        console.log(arr);
        dbconfig.query(sql,arr,async function(results){
            if(results.length > 0){
                let id = (type =='admin'?results[0].id:results[0].uid);
                console.log();
                let token =  await Token.setToken(username,id);
                res.json({
                    status:200,
                    profile:results[0],
                    msg:'登录成功',
                    token
                })
            }else{
                res.json({
                    status:400,
                    msg:'密码或者用户名错误'
                })
            }
            
        })
    
}

// 注册业务实现
handleRegister=(req,res)=>{
    let {username,password,email} = req.body;
    // 判断是否已经存在该用户
    operation.select('username',username,'user').then(success=>{
        // 如果已经存在用户名
        res.json({
        status:400,
        msg:'该用户已经存在'
    });},
    err=>{  
        // 执行注册操作
        password = md5(password);
        let sql = `insert into user(username,password,email) values(?,?,?)`;
        let arr=[username,password,email];
        dbconfig.query(sql,arr,function(results){
            console.log(sql);
    
            if(results.affectedRows > 0){
                console.log(results);
                res.json({
                    status:200,
                    username:username,
                    msg:'注册成功',
                })
            }else{
                res.json({
                    status:400,
                    msg:'注册失败'
                })
            }
            
        })})
    
      
       

}

module.exports={
    handleLogin,
    handleRegister
}
